package sistemaweb.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sistemaweb.excepcion.DAOExcepcion;
import sistemaweb.excepcion.LoginExcepcion;
import sistemaweb.modelo.Persona;
import sistemaweb.gestion.GestionPersona;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
			
		String correo = request.getParameter("username");
		String password = request.getParameter("password");
		
		GestionPersona gestion = new GestionPersona();
		
	
		
		try{
			Persona vo = gestion.ValidarPersona(correo, password);
			
			
			HttpSession session = request.getSession();
			session.setAttribute("USUARIO_ACTUAL", vo);
			
			//System.out.println(id.getCorreo());
			//System.out.println(vo.getIdUsuario());
			//System.out.println(vo);
			if(vo.getIdUsuario().equals("1")){
				response.sendRedirect("PrincipalServlet");
				return;				
			}
			
			if(vo.getIdUsuario().equals("2")){
				response.sendRedirect("HomeServlet");
				return;				
			}			
			//response.sendRedirect("PrincipalServlet");
			//return;
			//rd.forward(request, response);
			
		}catch (DAOExcepcion e){
			request.setAttribute("MENSAJE", "Hubo un error al procesar la operaci�n: " + e.getMessage());
		}catch (LoginExcepcion e){
			request.setAttribute("MENSAJE", "Usuario y/o clave incorrectos vuelve a intentar");
		}
		
		RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
		rd.forward(request, response);
	}

}
